package com.shanghaionstar.presenter;

import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.Uri;

import com.onstar.cn.auth.CheckNewVersion;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.onstar.cn.vehicle.entity.RequestStatus;
import com.onstar.cn.vehicle.result.PollingResult;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.MainTabActivity;
import com.shanghaionstar.activity.iview.IMainTabView;
import com.shanghaionstar.discover.geofence.GeofenceInfoActivity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.nav.NavLocationDialogActivity;
import com.shanghaionstar.nav.model.NavInfoModel;
import com.shanghaionstar.nav.model.PoiHistoryInfo;
import com.shanghaionstar.nav.service.NavService;
import com.shanghaionstar.remote.manager.RemoteOperateValidateHelper;
import com.shanghaionstar.remote.presenter.RemotePresenter;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.service.MainTabService;
import com.shanghaionstar.sqlite.SearchHistoryImpl;
import com.shanghaionstar.sqlite.TBTHistoryImpl;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BroadcastRefreshUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ConnectBroad;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.GetUri;
import com.shanghaionstar.utils.NavHolder;
import com.shanghaionstar.utils.PlaySoundUtil;

import rx.functions.Action1;

import static com.onstar.cn.mag.enumtype.RemoteCommandsType.COMMANDS_TBT_ROUTE;

/**
 * Created by 6335yz on 2016/7/22.
 */
public class MainTabPresenter extends BasePresenter {
    private TBTHistoryImpl tbtHistoryImpl;
    private SearchHistoryImpl searchHistoryImpl;
    private Context context;
    private BaseActivity baseActivity;
    private Context applicationContext;
    private ConnectBroad connectBroad;
    private NavService navService;
    private IMainTabView mainTabView;

    private MainTabService versionService;
    private BroadcastRefreshUtil broadcastUtil;


    public void initBroadcastUtil() {
        broadcastUtil = new BroadcastRefreshUtil(baseActivity);
        broadcastUtil.setOnResultListener(new BroadcastRefreshUtil.OnResultListener() {
            @Override
            public void onResult(int code, Object obj) {
                if (code == FinalConfigParams.SUCCESS) {
                    setBroadcastDatas((Long) obj);
                }
            }
        });
    }

    public void loadBroadcasts() {
        broadcastUtil.loadBroadcasts(baseActivity);
    }

    public void setBroadcastDatas(final long lastId) {
        long curId = PreferencesUtls.getInstance(baseActivity)
                .getLong(FinalConfigParams.BROADCAST_LAST_ID, -1L);
        if (curId < lastId) {
            PreferencesUtls.getInstance(baseActivity).putString(FinalConfigParams.BROADCAST_UNREAD,
                    FinalConfigParams.TRUE);
        } else {
            PreferencesUtls.getInstance(baseActivity).putString(FinalConfigParams.BROADCAST_UNREAD,
                    FinalConfigParams.FALSE);
        }
        if (baseActivity != null && baseActivity instanceof MainTabActivity) {
            baseActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ((MainTabActivity) baseActivity).showMark();
                }
            });
        }
    }

    public MainTabPresenter(IMVPScheduler mvpScheduler, Context context) {
        super(mvpScheduler);
        this.context = context;
        baseActivity = (BaseActivity) context;
        applicationContext = context.getApplicationContext();
        navService = new NavService(context);
        versionService = new MainTabService(context);

        //test
//        PollingResult pollingResult = new PollingResult();
//        pollingResult.setRequestType(RemoteCommandsType.COMMANDS_LOCATION.value());
//        pollingResult.setLat("31.16782");
//        pollingResult.setLon("121.396614");
//        pollingResult.setRequestStatus(RequestStatus.Success.getStringValue());
//        Location location = new Location("");
//        if (!CommonUtil.isNull(pollingResult.getLat())) {
//            location.setLatitude(Double.valueOf(pollingResult.getLat()));
//        }
//        if (!CommonUtil.isNull(pollingResult.getLon())) {
//            location.setLongitude(Double.valueOf(pollingResult.getLon()));
//        }
//        NavHolder.getInstance(context).setVehicleLocation(location);
//        NavHolder.getInstance(context).setVehicleLocationTime(pollingResult.getCompleteTime());
//        showMyDialog(pollingResult);
    }

    public void checkNewVersion() {
        subscription = versionService.checkNewVersion().subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<CheckNewVersion>() {
                    @Override
                    public void call(final CheckNewVersion checkNewVersion) {
                        String versionCode = checkNewVersion.getVersionCode();
                        int iVersionCode = Integer.valueOf(versionCode);
                        int localVersionCode = new DeviceUtil(context).getAppVersionCode();
                        String currentVersion = PreferencesUtls.getInstance(context)
                                .getString(FinalConstants.SharedPreferencesConfig.CURRENT_VERSION, "");
                        if ((CommonUtil.isNull(currentVersion) || !currentVersion.equalsIgnoreCase(versionCode)) && localVersionCode < iVersionCode) {
                            AlertDialogUtil.showAlertDialog(context, R.string.login_version_update,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent i = GetUri.getIntent(context);
                                            boolean b = GetUri.judge(context, i);
                                            if (b) {
                                                if (!CommonUtil.isNull(checkNewVersion.getUrlLocation())) {
                                                    Intent intent = new Intent("android.intent.action.VIEW");
                                                    intent.setData(Uri.parse(checkNewVersion.getUrlLocation()));
                                                    context.startActivity(intent);
                                                } else {
                                                    dialog.dismiss();
                                                }
                                            } else {
                                                context.startActivity(i);
                                            }
                                        }
                                    }, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            PreferencesUtls.getInstance(context).put(
                                                    FinalConstants.SharedPreferencesConfig.CURRENT_VERSION,
                                                    checkNewVersion.getVersionCode() + "");
                                        }
                                    });
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }


    public void onActivityFinish() {
        if (connectBroad != null) {
            context.unregisterReceiver(connectBroad);
        }
    }

    @Override
    public void setView(IMVPView view) {
        super.setView(view);
        mainTabView = (IMainTabView) view;

    }

    /**
     * 开启网络变化检测
     */
    public void initConnectBroad() {
        connectBroad = new ConnectBroad();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(connectBroad, intentFilter);
    }

    /**
     * 车辆位置回调
     *
     * @param pollingResult
     */
    public void vehicleLocateCallBack(PollingResult pollingResult) {
        if(getRunningActivityName().contains(GeofenceInfoActivity.class.getSimpleName()))
            return;
        Location location = new Location("");
        PlaySoundUtil.playDefaultSound(context, true);

        if (!CommonUtil.isNull(pollingResult.getLat())) {
            location.setLatitude(Double.valueOf(pollingResult.getLat()));
        }
        if (!CommonUtil.isNull(pollingResult.getLon())) {
            location.setLongitude(Double.valueOf(pollingResult.getLon()));
        }
        NavHolder.getInstance(context).setVehicleLocation(location);
        NavHolder.getInstance(context).setVehicleLocationTime(pollingResult.getCompleteTime());
        if (!NavHolder.getInstance(context).isShowMap()) {
            showMyDialog(pollingResult);
        } else {
            RxBus.getDefault().post(RxConstants.VEHICLE_LOCATE, pollingResult);
        }
    }

    private String getRunningActivityName(){
        ActivityManager activityManager=(ActivityManager)baseActivity.getSystemService(Context.ACTIVITY_SERVICE);
        String runningActivity=activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
        return runningActivity;
    }

    private void showMyDialog(final PollingResult pollingResult) {
//        Intent intent = new Intent(context, NavLocationDialogActivity.class);
//        intent.putExtra("pollingResult",pollingResult);
//        context.startActivity(intent);
        Intent intent = new Intent(context, NavLocationDialogActivity.class);
        intent.putExtra("pollingResult", pollingResult);
        context.startActivity(intent);
//        final Dialog dialog = new Dialog(context);
//        View view = LayoutInflater.from(context).inflate(R.layout.nav_vehicle_alert_dialog, null);
//        CustomButton dialog_confirm = (CustomButton) view.findViewById(R.id.dialog_confirm);
//        CustomButton dialog_cancel = (CustomButton) view.findViewById(R.id.dialog_cancel);
//        dialog_confirm.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(context, NavActivity.class);
//                intent.putExtra("isShowToMap", true);
//                intent.putExtra("pollingResult", pollingResult);
//                context.startActivity(intent);
//                dialog.dismiss();
//            }
//        });
//        dialog_cancel.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                dialog.dismiss();
//            }
//        });
//        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        dialog.setContentView(view);
//        //获取到当前Activity的Window
//        Window dialog_window = dialog.getWindow();
//        //获取到LayoutParams
//        WindowManager.LayoutParams dialog_window_attributes = dialog_window.getAttributes();
//        DisplayMetrics dm = new DisplayMetrics();
//        baseActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
//        //设置宽度
//        dialog_window_attributes.width = (int) (dm.widthPixels * 0.97);
//        //设置高度
//        dialog_window_attributes.height = (int) (dm.heightPixels * 0.35);
//        dialog_window.setAttributes(dialog_window_attributes);
////        dialog_window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//        dialog.show();
    }

    /**
     * 处理发送TBT/ODD返回主页后弹框
     */
    public void alertTBTODDDialog(PollingResult result) {
        if (RequestStatus.Success.getStringValue().equals(result.getRequestStatus())) {
            PlaySoundUtil.playDefaultSound(context, true);
            if (COMMANDS_TBT_ROUTE.value().equals(result.getRequestType())) {
                BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.SendingTBT.getStringValue(), ReportReqParam.getTBTOddReportParams(COMMANDS_TBT_ROUTE, true));
                ToastView toastView = new ToastView(context);
                toastView.showToast(context.getString(R.string.send_to_tbt_success));
            } else if (RemoteCommandsType.COMMANDS_NAV_DESTINATION.value().equals(result.getRequestType())) {
                BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.SendingODD.getStringValue(), ReportReqParam.getTBTOddReportParams(RemoteCommandsType.COMMANDS_NAV_DESTINATION, true));
                ToastView toastView = new ToastView(context);
                toastView.showToast(context.getString(R.string.send_to_odd_success));
            }
        } else if (RequestStatus.Failure.getStringValue().equals(result.getRequestStatus())) {
            if (COMMANDS_TBT_ROUTE.value().equals(result.getRequestType())) {
                BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.SendingTBT.getStringValue(), ReportReqParam.getTBTOddReportParams(COMMANDS_TBT_ROUTE, false, result.getErrorInfo() == null ? "" : result.getErrorInfo().getMsg()));
                BusinessUtil.showCommandFailToast(context.getString(R.string.send_to_tbt_failed), context, new Action1() {
                    @Override
                    public void call(Object o) {
                        if (NavHolder.getInstance(context).getCurrentSendPoi() != null) {
                            LogManager.getInstance().d("resend poi detail--->" + NavHolder.getInstance(context).getCurrentSendPoi().getLatitude());
                            sendTbtOrOdd(NavHolder.getInstance(context).getCurrentSendPoi());
                        }
                    }
                });
//                if(mainTabView!=null) {
//                    if(ApplicationUtil.isActivityFront(context)) {
//                        mainTabView.showAppFrontNavCommandFailToast(NavHolder.getInstance(context).getCurrentSendPoi());
//                    }else {
//                        mainTabView.showAppBackNavCommandFailToast(NavHolder.getInstance(context).getCurrentSendPoi());
//                    }
//                }
            } else if (RemoteCommandsType.COMMANDS_NAV_DESTINATION.value().equals(result.getRequestType())) {
                BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.SendingODD.getStringValue(), ReportReqParam.getTBTOddReportParams(RemoteCommandsType.COMMANDS_NAV_DESTINATION, false, result.getErrorInfo() == null ? "" : result.getErrorInfo().getMsg()));
                if (mainTabView != null) {
                    BusinessUtil.showCommandFailToast(context.getString(R.string.send_to_odd_failed), context, new Action1() {
                        @Override
                        public void call(Object o) {
                            sendTbtOrOdd(NavHolder.getInstance(context).getCurrentSendPoi());
                        }
                    });
                }
            }
        }
    }

    /**
     * 处理发送remote control 返回主页后弹框
     */
    public void vehicleRemoteControlCallBack(PollingResult pollingResult) {
        String functionId = RemotePresenter.getFunctionId(RemoteCommandsType.fromValue(pollingResult.getRequestType()));
        if (RequestStatus.Success.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
            BusinessUtil.sendReportByRequestParams(context, functionId, ReportReqParam.getRemoteCommandReportParams(functionId, true));
            new ToastView(context).showToast(AlertDialogUtil.getResultSystemAlertDialog(context, true, RemoteCommandsType.fromValue(pollingResult.getRequestType()), null, null));
            playSound(RemoteCommandsType.fromValue(pollingResult.getRequestType()));
        } else if (RequestStatus.Failure.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
            if (!CommonUtil.isNull(pollingResult.getErrorInfo())) {//如果是一般错误
                BusinessUtil.sendReportByRequestParams(context, functionId, ReportReqParam.getRemoteCommandReportParams(functionId, false, pollingResult.getErrorInfo().getMsg()));
                new ToastView(context).showToast(AlertDialogUtil.getResultSystemAlertDialog(context, false, RemoteCommandsType.fromValue(pollingResult.getRequestType()), pollingResult.getErrorInfo(), null));
                if (mainTabView != null) {
                    mainTabView.showRemoteFailDialog(pollingResult);
                }
            } else if (!CommonUtil.isNull(pollingResult.getHttpException())) {//如果是网络请求错误
                ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(context, pollingResult.getHttpException());
                BusinessUtil.sendReportByRequestParams(context, functionId,
                        ReportReqParam.getRemoteCommandReportParams(functionId, false, errorInfo.getMsg()));
                new ToastView(context).showToast(errorInfo.getMsg());
                if (mainTabView != null) {
                    mainTabView.showRemoteFailDialog(pollingResult);
                }
            }
        }
    }

    private void playSound(RemoteCommandsType remoteCommandsType) {
        switch (remoteCommandsType) {
            case COMMANDS_LOCK_DOOR:
            case COMMANDS_UNLOCK_DOOR:
                PlaySoundUtil.playCustomSound(context, true, R.raw.open_car);
                break;
            case COMMANDS_START:
                PlaySoundUtil.playCustomSound(context, true, R.raw.start_car);
                break;
            case COMMANDS_CANCEL_START:
                PlaySoundUtil.playCustomSound(context, true, R.raw.cancel_start);
                break;
            case COMMANDS_ALERT:
                PlaySoundUtil.playCustomSound(context, true, R.raw.whistle);
                break;
            default:
                break;
        }
    }

    public void sendTbtOrOdd(final PoiItemInfo poiItemInfo) {
        RemoteOperateValidateHelper helper = new RemoteOperateValidateHelper(baseActivity);
        helper.sendTbtOrOdd(poiItemInfo);


//        if(ApplicationUtil.getInstance().isCommanding){
//            ApplicationUtil.getInstance().controlCommand(context);
//            return;
//        }else {
//            ApplicationUtil.getInstance().isCommanding = true;
//        }
//        RemoteModel navInfoModel = new RemoteModel.Builder().create();
//        if (BusinessUtil.isServiceFeature(FeatureEnum.SENDNAVDESTINATION.value(), context)) {
//            if (PreferencesUtls.getInstance(context).getBoolean(FinalConstants.SharedPreferencesConfig.TBT_CHOOSE_SAVE, true)) {
//                navInfoModel.setRemoteCommandsType(RemoteCommandsType.COMMANDS_TBT_ROUTE);
//            } else if (PreferencesUtls.getInstance(context).getBoolean(FinalConstants.SharedPreferencesConfig.ODD_CHOOSE_SAVE, false)) {
//                navInfoModel.setRemoteCommandsType(RemoteCommandsType.COMMANDS_NAV_DESTINATION);
//            }
//        } else {
//            navInfoModel.setRemoteCommandsType(RemoteCommandsType.COMMANDS_TBT_ROUTE);
//        }
//        navInfoModel.poiItemInfo = poiItemInfo;

//        if(helper.validateTbtOrOdd(poiItemInfo,navInfoModel.getRemoteCommandsType())){
//            RemoteOperateManager.getInstance().init(baseActivity).exeRemote(navInfoModel.getRemoteCommandsType());
//        }

//        if (validateTbtOrOdd(poiItemInfo, navInfoModel.getRemoteCommandsType())) {
//            new AuthorUtil().reauthForNoPin(baseActivity, new Action1() {
//                @Override
//                public void call(Object o) {
//                    NavInfoModel tmp = new NavInfoModel();
//                    if (BusinessUtil.isServiceFeature(FeatureEnum.SENDNAVDESTINATION.value(), baseActivity)) {
//                        if (PreferencesUtls.getInstance(baseActivity).getBoolean(FinalConstants.SharedPreferencesConfig.TBT_CHOOSE_SAVE, true)) {
//                            tmp.remoteCommandsType = COMMANDS_TBT_ROUTE;
//                        } else if (PreferencesUtls.getInstance(baseActivity).getBoolean(FinalConstants.SharedPreferencesConfig.ODD_CHOOSE_SAVE, false)) {
//                            tmp.remoteCommandsType = RemoteCommandsType.COMMANDS_NAV_DESTINATION;
//                        }
//                    } else {
//                        tmp.remoteCommandsType = COMMANDS_TBT_ROUTE;
//                    }
//                    tmp.poiItemInfo = poiItemInfo;
//                    doNavCommand(tmp);
//                }
//            }, new Action1<Throwable>() {
//                @Override
//                public void call(Throwable throwable) {
//                    ApplicationUtil.getInstance().isCommanding =false;
//                    if (mainTabView != null) {
//                        ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(baseActivity, new HttpException("", throwable.getMessage()));
//                        mainTabView.onResponseError(new OnStarException("", errorInfo.getMsg()));
//                    }
//                }
//            });
//        }
    }

//    private boolean validateTbtOrOdd(PoiItemInfo poiItemInfo, RemoteCommandsType remoteCommandsType) {
//        if (poiItemInfo == null) return false;
//        if (remoteCommandsType != COMMANDS_TBT_ROUTE && remoteCommandsType != RemoteCommandsType.COMMANDS_NAV_DESTINATION)
//            return false;
//        if (!ApplicationUtil.getInstance().isLogin())
//            return false;
//        if (ApplicationUtil.getInstance().isAutoLogings()) {
//
//            if (mainTabView != null) {
//                mainTabView.onResponseError(new OnStarException("", context.getString(R.string.loading)));
//            }
//        }
//        if (!BusinessUtil.checkDriverOrProxyAndShowDialog(baseActivity)) {
//            return false;
//        }
//        if (!BusinessUtil.checkPackageRight(Constants.ENTITLEMENT_M05NAVIGATION, context, true)) {
//            return false;
//        }
//        //判断是否正在执行车辆的相关操作
//        if (BusinessUtil.checkInProgressCommand(context, null, false)) {
//            AlertDialogUtil.showAlertDialog(context, context.getString(R.string.dialog_warning),
//                    context.getString(R.string.service_inProcess_alert));
////            BusinessUtil.updateConfigValue(FinalConfigParams.SHARE_DESTINATION, "-1", context);
//            return false;
//        }
//        return true;
//    }

    private void doNavCommand(final NavInfoModel navInfoModel) {
        subscription = navService.doNavCommand(navInfoModel)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String requestId) {
                        if (navInfoModel.remoteCommandsType == RemoteCommandsType.COMMANDS_NAV_DESTINATION || navInfoModel.remoteCommandsType == COMMANDS_TBT_ROUTE) {
                            saveHistoryToSql(requestId, navInfoModel.poiItemInfo, null, true);
                            //将下发历史保存到历史记录中
                            saveSearchHistory(navInfoModel.poiItemInfo);
                        }
                        if (mainTabView != null) {
                            mainTabView.showCommandLoading(true);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        if (mainTabView != null) {
                            mainTabView.onResponseError((OnStarException) throwable);
                        }
                    }
                });
    }

    public void saveHistoryToSql(String requestId, PoiItemInfo poiItemInfo, String status, boolean isSave) {
        PoiHistoryInfo historyInfo = new PoiHistoryInfo();
        historyInfo.setPoiItemInfo(poiItemInfo);
        if (isSave) {
            historyInfo.setStatus("inProgress");
        } else {
            historyInfo.setStatus(status);
        }
        TBTHistoryImpl impl = new TBTHistoryImpl(context);
        impl.saveOrUpdateModelDestinationHistory(requestId, historyInfo, isSave);
    }

    /**
     * @param
     * @return void
     * @Title: saveSearchHistory
     * @Description: 保存到历史记录中
     */
    public void saveSearchHistory(PoiItemInfo poiItemInfo) {
        SearchHistoryImpl impl = new SearchHistoryImpl(context);
        impl.saveSearchHistory(poiItemInfo);
        RxBus.getDefault().post(RxConstants.ALL_PAGE_REFRESH, RxConstants.NAV_SAVE_POI);

    }
}
